import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.supercsv.io.CsvListReader;
import org.supercsv.prefs.CsvPreference;


public class CSVParser {

    /* ======================================================
     * MEMBERS
     * ====================================================== */
    private CsvListReader _listReader;
    private Boolean _header;

    /* ======================================================
     * CONSTRUCTORS
     * ====================================================== */
    public CSVParser(String filename, Boolean header){
	try {
		_listReader = new CsvListReader(new FileReader(filename), CsvPreference.EXCEL_PREFERENCE);
	    //_listReader = new CsvListReader(new FileReader("sidewalkCafes.csv"), CsvPreference.EXCEL_PREFERENCE);
	    _header = header;	    
	} catch (FileNotFoundException e) {
	    e.printStackTrace(); 
	}
    }

    /* ======================================================
     * METHODS
     * ====================================================== */
    public TransactionList parse(){
	try {
	    TransactionList returnList = new TransactionList();
	    // If the file has a header, move the cursor to the second row
	    if (_header){
		_listReader.getCSVHeader(true);
	    }

	    //Read in the contents from the csv file
	    List<String> list = _listReader.read();
	    while (list != null){
		//Sort the list by item
		Collections.sort(list);
		// Add a new transaction into the return list
		returnList.add(new Transaction((ArrayList<String>)list));
		// Read in the contents of the next row from the csv file
		list = _listReader.read();
	    }
	    return returnList;
	} catch (IOException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	    return null;
	}
    }
}

